package com.yupi.yupao.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.yupao.common.ErrorCode;
import com.yupi.yupao.exception.BusinessException;
import com.yupi.yupao.mapper.TeamMapper;
import com.yupi.yupao.model.domain.Team;
import com.yupi.yupao.model.domain.User;
import com.yupi.yupao.model.domain.UserTeam;
import com.yupi.yupao.model.dto.TeamQuery;
import com.yupi.yupao.model.enums.TeamStatusEnum;
import com.yupi.yupao.model.request.TeamJoinRequest;
import com.yupi.yupao.model.request.TeamQuitRequest;
import com.yupi.yupao.model.request.TeamUpdateRequest;
import com.yupi.yupao.model.vo.TeamUserVO;
import com.yupi.yupao.model.vo.UserVO;
import com.yupi.yupao.service.TeamService;
import com.yupi.yupao.service.UserService;
import com.yupi.yupao.service.UserTeamService;
import org.apache.commons.lang3.StringUtils;
import org.redisson.api.RLock;
import org.redisson.api.RedissonClient;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import org.apache.commons.collections4.CollectionUtils;

import javax.annotation.Resource;
import java.util.*;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;

/**
 * @author ROG
 * @description 针对表【team(队伍)】的数据库操作Service实现
 * @createDate 2025-02-08 22:13:37
 */
@SuppressWarnings({"all"})
@Service
public class TeamServiceImpl extends ServiceImpl<TeamMapper, Team>
        implements TeamService {

    @Resource
    private UserTeamService userTeamService;

    @Resource
    private UserService userService;

    @Resource
    private RedissonClient redissonClient;

    /**
     * 创建队伍接口系统设计
     * 业务逻辑
     *
     * @param team
     * @param loginUser
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public long addTeam(Team team, User loginUser) {
        //1、请求参数是否为空
        if (team == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //2、是否登录，未登录的不允许创建
        if (loginUser == null) {
            throw new BusinessException(ErrorCode.NOT_LOGIN);
        }
        final long userId = loginUser.getId();
        //3、检验信息
        //1.队伍人数>1且<=20
        int maxNum = Optional.ofNullable(team.getMaxNum()).orElse(0);
        if (maxNum < 1 || maxNum > 20) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍人数不满足要求");
        }
        //2. 队伍标题 <= 20
        String name = team.getName();
        if (name.length() > 20 || StringUtils.isBlank(name)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍标题不满足要求");
        }
        //   3. 描述 <= 512
        String description = team.getDescription();
        if (description.length() > 512 && StringUtils.isNotBlank(description)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍描述不满足要求");
        }
        //   5. 如果 status 是加密状态，一定要有密码，且密码 <= 32 这里创建一个枚举类
        int status = Optional.ofNullable(team.getStatus()).orElse(0);
        //获取对应枚举类
        TeamStatusEnum statusEnum = TeamStatusEnum.getEnumByValue(status);
        if (statusEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍状态不满足要求");
        }
        //判断密码是否满足要求
        String password = team.getPassword();
        if (TeamStatusEnum.SECRET.equals(statusEnum)) {
            if (password.length() > 32 || StringUtils.isBlank(password)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍密码设置不正确");
            }
        }
        // 6. 超时时间 > 当前时间
        Date expireTime = team.getExpireTime();
        if (new Date().after(expireTime)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "超时时间 > 当前时间");
        }
        // 7. 校验用户最多创建 5 个队伍 用前面获取的登录用户id获取
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId); // 根据登录用户id查询所有的队伍记录
        //获取所有的当前登录用户创建的队伍总数
        long hasTeamNum = this.count(queryWrapper);
        if (hasTeamNum >= 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户最多创建 5 个队伍");
        }
        // 8. 插入队伍信息到队伍表
        team.setId(null); //主键自增
        team.setUserId(userId); //设置队伍主人
        boolean result = this.save(team);
        /**
         * 这行代码获取 team 对象的 id 属性值，也就是新创建队伍在数据库中的 ID。
         * 在使用数据库自增主键策略时，MyBatis-Plus 会在插入成功后自动将数据库分配的自增 ID
         * 回填到 team 对象的 id 属性中。
         */
        Long teamId = team.getId();
        if (!result || teamId == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "创建队伍失败");
        }
        // 9. 插入用户  => 队伍关系到关系表
        UserTeam userTeam = new UserTeam();
        userTeam.setUserId(userId);
        userTeam.setTeamId(teamId);
        userTeam.setJoinTime(new Date());
        result = userTeamService.save(userTeam);
        if (!result) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "创建队伍失败");
        }
        return teamId;
    }

    /**
     * 搜索队伍业务逻辑代码
     *
     * @param teamQuery：查询请求体
     * @param isAdmin
     * @return
     */
    @Override
    public List<TeamUserVO> listTeams(TeamQuery teamQuery, boolean isAdmin) {
        //1从请求参数中取出队伍名称等查询条件，如果存在则作为查询条件
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        if (teamQuery != null) {
            //如果查询请求体不为空 则组合查询条件
            Long id = teamQuery.getId();
            if (id != null && id > 0) {
                queryWrapper.eq("id", id);
            }
            List<Long> idList = teamQuery.getIdList();
            if (CollectionUtils.isNotEmpty(idList)) {
                queryWrapper.in("id", idList);
            }
            //搜索条件查询 支持关键词和队伍名称查询
            //可以通过某个关键词同时对名称和描述查询
            String searchText = teamQuery.getSearchText();
            if (StringUtils.isNotBlank(searchText)) {
                queryWrapper.and(qw -> qw.like("name", searchText).or().like("description", searchText));
            }
            //队伍名称
            String name = teamQuery.getName();
            if (StringUtils.isNotBlank(name)) {
                queryWrapper.like("name", name);
            }
            //评论->描述
            String description = teamQuery.getDescription();
            if (StringUtils.isNotBlank(description)) {
                queryWrapper.like("description", description);
            }
            //最大人数匹配的
            Integer maxNum = teamQuery.getMaxNum();
            //查询最大人数相等的
            if (maxNum != null && maxNum > 0) {
                queryWrapper.eq("maxNum", maxNum);
            }
            // 根据状态来查询
            Integer status = teamQuery.getStatus();
            TeamStatusEnum statusEnum = TeamStatusEnum.getEnumByValue(status);
            if (statusEnum == null) {
                //如果枚举值不存在 则默认查询的队伍为公开状态
                statusEnum = TeamStatusEnum.PUBLIC;
            }
            /**
             * todo 思考这里的逻辑->区分公开和加密的房间->finished
             */
            //只有管理员才能查看加密还有非公开的房间 ->如果不是管理员同时查询状态为私有房间
            if (!isAdmin && statusEnum.equals(TeamStatusEnum.PRIVATE)) {
                throw new BusinessException(ErrorCode.NO_AUTH);
            }
            //状态查询
            queryWrapper.eq("status", statusEnum.getValue());
        }
        //不展示已过期的队伍（根据过期时间筛选）
        queryWrapper.and(qw -> {
            qw.gt("expireTime", new Date()).or().isNull("expireTime");
        });
        //查询一遍
        List<Team> teamList = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(teamList)) {
            return new ArrayList<>();
        }
        //todo 增加逻辑返回我加入的队伍已加入队伍的人数 每个队伍分别统计已加入队伍的人数 不需要更新hasJoin字段 finished
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        //获取上面的我创建的队伍id
        List<Long> teamIdList = teamList.stream().map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        //根据队伍ID查询已加入队伍的人数
        userTeamQueryWrapper.in("teamId",teamIdList);
        //查询到用户 队伍关联信息集合
        List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
        //在根据TeamId进行分组统计人数 键:队伍ID 值:用户队伍关系 1->[1,2,3]
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(item -> {
            return item.getTeamId();
        }));
        List<TeamUserVO> teamUserVOList = new ArrayList<>();
        //关联查询已加入队伍的用户信息 将已经进入到该队伍的用户返回给controller层返回
        for (Team team : teamList) {
            Long userId = team.getUserId();
            if (userId == null) {
                continue;
            }
            User user = userService.getById(userId);
            TeamUserVO teamUserVO = new TeamUserVO();
            BeanUtils.copyProperties(team, teamUserVO);
            //脱敏用户信息
            if (user != null) {
                UserVO userVO = new UserVO();
                BeanUtils.copyProperties(user, userVO);
                teamUserVO.setCreateUser(userVO);
            }
            teamUserVOList.add(teamUserVO);
        }
        //设置每个队伍都加入了多少人
        for (TeamUserVO team : teamUserVOList) {
            team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(),new ArrayList<>()).size());
        }
        return teamUserVOList;
    }

    /**
     * 获取我创建的队伍 业务逻辑接口优化->获取不了私密的房间
     *
     * @param teamQuery
     * @param isAdmin
     * @return
     */
    @Override
    public List<TeamUserVO> listTeamsNew(TeamQuery teamQuery, boolean isAdmin) {
        //1从请求参数中取出队伍名称等查询条件，如果存在则作为查询条件
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        if (teamQuery != null) {
            //查询userId用户创建的队伍
            Long userId = teamQuery.getUserId();
            if (userId != null && userId > 0) {
                queryWrapper.eq("userId", userId);
            }
            // 根据状态来查询
            Integer status = teamQuery.getStatus();
            TeamStatusEnum statusEnum = TeamStatusEnum.getEnumByValue(status);
            if (statusEnum == null) {
                //如果枚举值不存在 则默认查询的队伍为公开状态
                statusEnum = TeamStatusEnum.PUBLIC;
            }
            /**
             * todo 思考这里的逻辑->finished
             */
            //只有管理员才能查看加密还有非公开的房间 ->如果不是管理员同时查询状态为私有房间
            if (!isAdmin && statusEnum.equals(TeamStatusEnum.PRIVATE)) {
                throw new BusinessException(ErrorCode.NO_AUTH);
            }
            //状态查询
            queryWrapper.eq("status", statusEnum.getValue());
        }
        //不展示已过期的队伍（根据过期时间筛选）
        queryWrapper.and(qw -> {
            qw.gt("expireTime", new Date()).or().isNull("expireTime");
        });
        //查询一遍
        List<Team> teamList = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(teamList)) {
            return new ArrayList<>();
        }
        //todo 增加逻辑返回我创建的队伍已加入队伍的人数 每个队伍分别统计已加入队伍的人数 不需要更新hasJoin字段 finished
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        //获取上面的我创建的队伍id
        List<Long> teamIdList = teamList.stream().map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        //根据队伍ID查询已加入队伍的人数
        userTeamQueryWrapper.in("teamId",teamIdList);
        //查询到用户 队伍关联信息集合
        List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
        //在根据TeamId进行分组统计人数 键:队伍ID 值:用户队伍关系 1->[1,2,3]
        Map<Long, List<UserTeam>> teamIdUserTeamList = userTeamList.stream().collect(Collectors.groupingBy(item -> {
            return item.getTeamId();
        }));
        List<TeamUserVO> teamUserVOList = new ArrayList<>();
        //关联查询已加入队伍的用户信息 将已经进入到该队伍的用户返回给controller层返回 todo 同时设置已加入队伍人数
        for (Team team : teamList) {
            //获取队伍创建者ID
            Long userId = team.getUserId();
            if (userId == null) {
                continue;
            }
            //获取该队伍创建者
            User user = userService.getById(userId);
            TeamUserVO teamUserVO = new TeamUserVO();
            //拷贝一部分信息
            BeanUtils.copyProperties(team, teamUserVO);
            //脱敏用户信息
            if (user != null) {
                UserVO userVO = new UserVO();
                BeanUtils.copyProperties(user, userVO);
                teamUserVO.setCreateUser(userVO);
            }
            teamUserVOList.add(teamUserVO);
        }
        //设置每个队伍都加入了多少人
        for (TeamUserVO team : teamUserVOList) {
            team.setHasJoinNum(teamIdUserTeamList.getOrDefault(team.getId(),new ArrayList<>()).size());
        }
        return teamUserVOList;
    }

    /**
     * 获取我创建的队伍列表id
     * @param teamQuery
     * @param isAdmin
     * @return
     */
    @Override
    public List<Long> getTeamByMyself(TeamQuery teamQuery, boolean isAdmin) {
        //1从请求参数中取出队伍名称等查询条件，如果存在则作为查询条件
        QueryWrapper<Team> queryWrapper = new QueryWrapper<>();
        if (teamQuery != null) {
            Long userId = teamQuery.getUserId();
            if (userId != null && userId > 0) {
                queryWrapper.eq("userId", userId);
            }
            // 根据状态来查询
            Integer status = teamQuery.getStatus();
            TeamStatusEnum statusEnum = TeamStatusEnum.getEnumByValue(status);
            if (statusEnum == null) {
                //如果枚举值不存在 则默认查询的队伍为公开状态
                statusEnum = TeamStatusEnum.PUBLIC;
            }
            /**
             * todo 思考这里的逻辑->finished
             */
            //只有管理员才能查看加密还有非公开的房间 ->如果不是管理员同时查询状态为私有房间
            if (!isAdmin && TeamStatusEnum.PRIVATE.equals(statusEnum)) {
                throw new BusinessException(ErrorCode.NO_AUTH);
            }
            //状态查询
            queryWrapper.eq("status", statusEnum.getValue());
        }
        //不展示已过期的队伍（根据过期时间筛选）
        queryWrapper.and(qw -> {
            qw.gt("expireTime", new Date()).or().isNull("expireTime");
        });
        //查询一遍
        List<Team> teamList = this.list(queryWrapper);
        if (CollectionUtils.isEmpty(teamList)) {
            return new ArrayList<>();
        }
        List<Long> result = teamList.stream().map(item -> {
            return item.getId();
        }).collect(Collectors.toList());
        return result;
    }

    /**
     * 更新队伍信息 业务逻辑 todo 选择更新 待实现 finished
     *
     * @param team
     * @param loginUser
     * @return
     */
    @Override
    public boolean updateTeam(TeamUpdateRequest team, User loginUser) {
        //获取登录的用户id
        final long userId = loginUser.getId();
        //1、判断请求体是否为空
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "请求数据为空");
        }
        //2、查询队伍是否存在
        //获取队伍id
        Long TeamId = team.getId();
        if (TeamId == null || TeamId <= 0) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "队伍不存在");
        }
        //3、只有管理员或者队伍的创建者可以修改队伍信息
        boolean admin = userService.isAdmin(loginUser);
        Team userTeam = this.getById(TeamId);
        if (userTeam == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "队伍不存在");
        }
        //如果不是管理员或者队伍的创建者则抛出异常信息
        if (!admin && userTeam.getUserId() != userId) {
            throw new BusinessException(ErrorCode.NO_AUTH, "只有管理员或者队伍的创建者可以修改队伍信息");
        }
        //todo 4、如果用户传入的新值和老值一致就不用更改了 finished
        //获取老的队伍值
        TeamUpdateRequest teamUpdateRequest = new TeamUpdateRequest();
        Team team1 = this.getById(TeamId);
        BeanUtils.copyProperties(team1, teamUpdateRequest);
        if (team.equals(teamUpdateRequest)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "传入的新值和老值一致");
        }
        //5、如果队伍更改为加密，必须要有密码
        String password = team.getPassword();
        Integer status = team.getStatus();
        TeamStatusEnum enumByValue = TeamStatusEnum.getEnumByValue(status);
        if (TeamStatusEnum.SECRET.equals(enumByValue)) {
            if (StringUtils.isEmpty(password)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "房间必须要有密码,当前房间的密码是空的");
            }
        }
        //6、提交更改请求
        Team newTeam = new Team();
        BeanUtils.copyProperties(team, newTeam);
        return this.updateById(newTeam);
    }

    /**
     * 用户加入队伍的业务逻辑
     *
     * @param team
     * @param loginUser
     * @return
     */
    @Transactional(rollbackFor = Exception.class)
    @Override
    public boolean joinTeam(TeamJoinRequest team, User loginUser) {
        //判空
        if (team == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "请求参数为空");
        }
        final long userId = loginUser.getId();
        //2、队伍必须存在，只能加入未满，未过期的队伍
        Long teamId = team.getTeamId();
        if (teamId == null || teamId <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Team teamold = this.getById(teamId);
        if (teamold == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "队伍不存在");
        }
        //获取过期时间
        Date expireTime = teamold.getExpireTime();
        if (expireTime != null && new Date().after(expireTime)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍已过期");
        }
        //4、禁止加入私有的队伍
        Integer status = teamold.getStatus();
        TeamStatusEnum privateTeam = TeamStatusEnum.getEnumByValue(status);
        if (TeamStatusEnum.PRIVATE.equals(privateTeam)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "禁止加入私有队伍");
        }
        //5、如果加入的队伍是加密的，必须密码匹配才可以
        String password = team.getPassword();
        if (TeamStatusEnum.SECRET.equals(privateTeam)) {
            if (StringUtils.isBlank(password) || !password.equals(teamold.getPassword())) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "加密房间需要输入密码/密码错误");
            }
        }
        //todo redisson实现分布式锁解决一个用户重复加入队伍的问题 finished
        //获取锁保证只有一个线程能获取到锁
        RLock lock = redissonClient.getLock("yupao:join_team");
        try {
            //抢到锁并执行业务逻辑
            while (true) {
                /**
                 lock.tryLock(0, -1, TimeUnit.MILLISECONDS) 尝试获取锁，其中 0 表示等待获取锁的时间为 0 毫秒，
                 -1 表示锁的过期时间为永久（不过在实际使用中，建议设置合理的过期时间以避免死锁）。
                 如果成功获取到锁，则执行后续的缓存预热操作。
                 */
                if (lock.tryLock(0, -1, TimeUnit.MILLISECONDS)) {
                    System.out.println("getLock: " + Thread.currentThread().getId());
                    //获取此时已经加入的队伍的人数
                    QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>(); //重新new空间
                    //1、一个用户最多加入5个队伍->关联表->事务
                    queryWrapper.eq("userId", userId);
                    long count = userTeamService.count(queryWrapper);
                    if (count >= 5) {
                        throw new BusinessException(ErrorCode.NO_AUTH, "一个用户最多同时可以创建和加入5个队伍");
                    }
                    //3、不能加入自己创建的队伍,不能重复加入已经加入的队伍 todo 这里有问题->finished
                    if (teamold.getUserId() == userId) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户已加入该队伍");
                    }
                    //不能重复加入已加入的队伍
                    queryWrapper = new QueryWrapper<>(); //重新new空间
                    queryWrapper.eq("userId", userId);
                    queryWrapper.eq("teamId", teamId);
                    long count2 = userTeamService.count(queryWrapper);
                    if (count2 > 0) {
                        throw new BusinessException(ErrorCode.PARAMS_ERROR, "不能重复加入队伍");
                    }
                    queryWrapper = new QueryWrapper<>();
                    queryWrapper.eq("teamId", teamId);
                    long count1 = userTeamService.count(queryWrapper);
                    //获取队伍的最大人数
                    Integer maxNum = teamold.getMaxNum();
                    if (maxNum <= count1) {
                        throw new BusinessException(ErrorCode.NO_AUTH, "队伍人数已满");
                    }

                    //6、提交加入队伍，提交队伍关联表
                    UserTeam userTeam = new UserTeam();
                    userTeam.setUserId(userId);
                    userTeam.setTeamId(teamId);
                    userTeam.setJoinTime(new Date());
                    boolean save = userTeamService.save(userTeam);
                    return save;
                }
            }
        } catch (InterruptedException e) {
            log.error("doCacheRecommendUser error", e);
            return false;
        } finally {
            //释放自己的锁 判断当前线程是否有锁存在
            if (lock.isHeldByCurrentThread()) {
                //如果有锁存在就释放自己的锁
                System.out.println("unLock: " + Thread.currentThread().getId());
                lock.unlock();
            }
        }
    }

    /**
     * 用户退出当前队伍的业务逻辑
     *
     * @param team
     * @param loginUser todo 1、测试两人及以上队伍退出->finished
     *                  todo 2、测试队长退出将队长转移给顺位的人->finished
     * @return 移除关系
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean quitTeam(TeamQuitRequest team, User loginUser) {
        //再次判空->是不是有点多余
        if (team == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR);
        }
        //1、校验队伍是否存在
        final Long teamId = team.getTeamId();
        if (teamId == null || teamId <= 0) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "队伍不存在");
        }
        Team teamById = this.getById(teamId);
        //获取队伍信息
        String name = teamById.getName();
        if (teamById == null) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "队伍不存在");
        }
        //2、校验登录用户是否已加入当前队伍->联查
        final long userId = loginUser.getId();
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userId", userId);
        queryWrapper.eq("teamId", teamId);
        long count2 = userTeamService.count(queryWrapper);
        if (count2 == 0) {
            throw new BusinessException(ErrorCode.NO_AUTH, "用户没加入当前队伍");
        }
        //3、退出队伍
        //3.1 队伍只剩一个人 则直接解散 -> 此时只有创建者在这个队伍 或者 创建者提前退出了但是还有一个人
        //查询该队伍的人数
        long countNum = this.countTeamUserByTeamId(teamId);
        if (countNum == 1) {
            //队伍表直接删除
            this.removeById(teamId);
//            //关联表删除相关关联
//            queryWrapper = new QueryWrapper<>();
//            queryWrapper.eq("userId", userId);
//            queryWrapper.eq("teamId", teamId);
//            UserTeam one = userTeamService.getOne(queryWrapper);
//            userTeamService.removeById(one);
        } else {
            //3.2 还有2人以及两人以上 如果是非队长则自己退出->逻辑就是直接删除用户队伍关联表的信息
            // 如果是队长退出,权限转移给第二早加入的用户----->先来后到 只用取用户id最小的两条数据->因为id是自增的,时间越大id越大
            if (teamById.getUserId() == userId) {
                //把队伍转移给最早加入的用户
                //1.查询已经加入队伍的所有用户和加入时间
                QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
                userTeamQueryWrapper.eq("teamId", teamId);
                userTeamQueryWrapper.last("order by id asc limit 2"); //在sql语句最后连接自定义的sql片段
                List<UserTeam> userTeamList = userTeamService.list(userTeamQueryWrapper);
                if (CollectionUtils.isEmpty(userTeamList) || userTeamList.size() <= 1) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR);
                }
                //更新队长信息
                UserTeam userTeam = userTeamList.get(1);
                Long nextTeamLeaderId = userTeam.getUserId();
                Team updateTeam = new Team();
                updateTeam.setId(teamId);
                updateTeam.setUserId(nextTeamLeaderId);
                boolean result = this.updateById(updateTeam);
                if (!result) {
                    throw new BusinessException(ErrorCode.SYSTEM_ERROR, "更新队伍队长失败");
                }
            }
            //如果不是队长 直接删除关联关系退出队伍
        }
        // 移除关系 关联表信息
        return userTeamService.remove(queryWrapper);
    }

    /**
     * 解散队伍
     *
     * @param id:队伍id
     * @param loginUser:当前登录用户
     * @return
     */
    @Override
    @Transactional(rollbackFor = Exception.class)
    public boolean deleteTeam(long id, User loginUser) {
        //1、校验请求参数
        if (id <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍不存在");
        }
        //2、校验队伍是否存在
        Team team = this.getById(id);
        if (team == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "队伍不存在");
        }
        //3、校验当前登录用户是不是队长
        if (!team.getUserId().equals(loginUser.getId())) {
            throw new BusinessException(ErrorCode.FORBIDDEN, "无权限解散部队");
        }
        //4、移除所有加入队伍的关联信息
        QueryWrapper<UserTeam> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("teamId", id);
        boolean remove = userTeamService.remove(queryWrapper);
        if (!remove) {
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "删除队伍关联信息失败");
        }
        //5、解散队伍
        return this.removeById(id);
    }

    /**
     * 获取某队伍当前人数
     *
     * @param teamId
     * @return
     */
    private long countTeamUserByTeamId(long teamId) {
        QueryWrapper<UserTeam> userTeamQueryWrapper = new QueryWrapper<>();
        userTeamQueryWrapper.eq("teamId", teamId);
        return userTeamService.count(userTeamQueryWrapper);
    }
}




